﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.MaterialPlanning;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialPlanning
{
    /// <summary>
    /// 物料需求计划删除Handler
    /// </summary>
    public class DeletePlanHandler : IRequestHandler<DeletePlanCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料需求计划表仓储
        /// </summary>
        public readonly IBaseRepository<Plan> planrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletePlanHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="planrepository"></param>
        /// <param name="logger"></param>
        public DeletePlanHandler(IMapper mapper, IBaseRepository<Plan> planrepository, ILogger<DeletePlanHandler> logger)
        {
            this.mapper = mapper;
            this.planrepository = planrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 物料需求计划删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DeletePlanCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Deleted };
            try
            {
                var list = await(await planrepository.GetAll()).Where(d => d.PlanId == request.PlanId).FirstAsync();
                if (list != null)
                {
                    list.IsDel = 2;
                }
                var res = planrepository.Update(list);
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "物料需求计划删除成功";
            }
            catch (Exception ex)
            {
                logger.LogError("物料需求计划删除异常");
                result.Msg = "物料需求计划删除异常";
            }
            return result;
        }
    }
}
